window.addEventListener('load', () => {
  (function () {
    function Food(obj) {
      obj = obj || {}
      this.x = obj.x || 0
      this.y = obj.y || 0
    
      this.width = obj.width || 20
      this.height = obj.height || 20
    
      this.color = obj.color || 'orange'
    }
    
    let foodArr = []
    let position = 'absolute'
    // 渲染食物
    Food.prototype.render = function(map) {
      // 删除之前的食物
      delFood()
      // 随机生成食物
      this.x = Tools.getRandom(0, map.offsetWidth/this.width - 1) * this.width
      this.y = Tools.getRandom(0, map.offsetHeight/this.width - 1) * this.height
  
      let div = document.createElement('div')
      map.appendChild(div)
  
      // 记录食物
      foodArr.push(div)
  
      // 设置div样式
      div.style.position = position
      div.style.left = this.x + 'px'
      div.style.top = this.y + 'px'
      div.style.width = this.width + 'px'
      div.style.height = this.height + 'px'
      div.style.backgroundColor = this.color
    }
    
    // 删除食物方法
    function delFood() {
      for (let i = foodArr.length - 1; i >= 0; i--) {
        foodArr[i].parentNode.removeChild(foodArr[i])
        foodArr.splice(i, 1)
      }
    }
    window.Food = Food
  })()
  

  // 测试
  // let map = document.getElementById('map')
  // let food = new Food()
  // food.render(map)
})